package org.vacoor.nothing.ui.hotkey.impl.linux;

import jxgrabkey.HotkeyConflictException;
import jxgrabkey.HotkeyListener;
import jxgrabkey.JXGrabKey;
import org.vacoor.nothing.ui.hotkey.EmptyOSHotKeyBinder;
import org.vacoor.nothing.ui.hotkey.OSHotKeyEvent;
import org.vacoor.nothing.ui.hotkey.OSHotKeyListener;

import javax.swing.*;

/**
 * @author: Vacoor
 */
class JXGrabKeyBinder extends EmptyOSHotKeyBinder implements HotkeyListener {
    private JXGrabKey jxGrabKey;

    public JXGrabKeyBinder(JXGrabKey jxGrabKey, int identifier) {
        super(identifier);
        this.jxGrabKey = jxGrabKey;
    }

    @Override
    public boolean doRegisterHotKey(int modifiers, int key) {
        try {
            jxGrabKey.removeHotkeyListener(this);
            jxGrabKey.unregisterHotKey(getIdentifier());
            jxGrabKey.registerAwtHotkey(getIdentifier(), modifiers, key);
            jxGrabKey.addHotkeyListener(this);
            return true;
        } catch (HotkeyConflictException e) {
            return false;
        }
    }

    /**
     * JXGrabKey 回调
     */
    @Override
    public void onHotkey(int i) {
        if (getIdentifier() == i) {
            final OSHotKeyEvent event = new OSHotKeyEvent(getIdentifier(), getModifiers(), getKey());
            for (final OSHotKeyListener l : getOSHotKeyListeners()) {
                SwingUtilities.invokeLater(
                        new Runnable() {
                            @Override
                            public void run() {
                                l.onOSHotKey(event);
                            }
                        }
                );
            }
        }
    }
}
